import { useState, useEffect } from "react";
import styles from "./BoxManageQuery.module.css";

// 定义箱子数据类型（匹配API返回的字段名）
interface BoxData {
    id: number;
    boxName: string;
    long: number;
    wide: number;
    high: number;
    state: number;
    remark?: string; // 备注字段
}

// 定义添加箱子的表单数据类型
interface BoxFormData {
    id?: number;
    boxName: string;
    long: string;
    wide: string;
    high: string;
    remark: string;
    state: number;
}

// 定义表单错误类型
interface FormErrors {
    boxName?: string;
    long?: string;
    wide?: string;
    high?: string;
}

const BoxManageQuery = () => {
    // 状态管理
    const [boxList, setBoxList] = useState<BoxData[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string>("");
    const [refreshing, setRefreshing] = useState<boolean>(false);
    const [showModal, setShowModal] = useState<boolean>(false);
    const [isEditing, setIsEditing] = useState<boolean>(false);
    
    // 表单数据
    const [formData, setFormData] = useState<BoxFormData>({
        boxName: "",
        long: "",
        wide: "",
        high: "",
        remark: "",
        state: 1
    });
    
    // 表单错误
    const [formErrors, setFormErrors] = useState<FormErrors>({});

    // 获取箱子列表数据
    const fetchBoxList = async () => {
        try {
            setLoading(true);
            setError("");
            setRefreshing(true);
            
            console.log('开始获取箱子列表数据...');
            
            const response = await fetch('http://localhost:5233/api/BoxManage/GetBoxList', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            console.log('API返回的数据:', data);

            // 处理不同的API响应格式
            let boxData: BoxData[] = [];
            
            if (Array.isArray(data)) {
                boxData = data;
            } else if (data && Array.isArray(data.data)) {
                boxData = data.data;
            } else if (data && Array.isArray(data.result)) {
                boxData = data.result;
            } else if (data && typeof data === 'object') {
                const possibleArrayFields = ['items', 'list', 'boxes', 'content'];
                for (const field of possibleArrayFields) {
                    if (Array.isArray(data[field])) {
                        boxData = data[field];
                        break;
                    }
                }
            }

            if (!Array.isArray(boxData)) {
                console.error('API返回的数据不是数组格式:', data);
                throw new Error('服务器返回的数据格式不正确');
            }

            console.log('处理后的箱子数据:', boxData);
            setBoxList(boxData);
            
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : '获取数据失败';
            console.error('获取箱子列表失败:', err);
            setError(errorMessage);
            setBoxList([]);
        } finally {
            setLoading(false);
            setRefreshing(false);
        }
    };

    useEffect(() => {
        fetchBoxList();
    }, []);

    // 表单验证
    const validateForm = (): boolean => {
        const errors: FormErrors = {};
        let isValid = true;

        if (!formData.boxName.trim()) {
            errors.boxName = "名称不能为空";
            isValid = false;
        }

        if (!formData.long || isNaN(Number(formData.long)) || Number(formData.long) <= 0) {
            errors.long = "请输入有效的长度";
            isValid = false;
        }

        if (!formData.wide || isNaN(Number(formData.wide)) || Number(formData.wide) <= 0) {
            errors.wide = "请输入有效的宽度";
            isValid = false;
        }

        if (!formData.high || isNaN(Number(formData.high)) || Number(formData.high) <= 0) {
            errors.high = "请输入有效的高度";
            isValid = false;
        }

        setFormErrors(errors);
        return isValid;
    };

    // 处理表单提交
    const handleSubmit = async () => {
        if (!validateForm()) {
            return;
        }

        try {
            const url = isEditing 
                ? 'http://localhost:5233/api/BoxManage/Updatebox'
                : 'http://localhost:5233/api/BoxManage/AddBox';

            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: formData.id,
                    boxName: formData.boxName,
                    long: Number(formData.long),
                    wide: Number(formData.wide),
                    high: Number(formData.high),
                    remark: formData.remark,
                    state: formData.state
                }),
            });

            const data = await response.json();
            
            if (data.code === 200) {
                // 先关闭弹窗
                handleCloseModal();
                // 刷新列表
                await fetchBoxList();
                // 最后显示成功提示
                setTimeout(() => {
                    alert(isEditing ? '修改成功' : '添加成功');
                }, 100);
            } else {
                throw new Error(data.message || (isEditing ? '修改失败' : '添加失败'));
            }
        } catch (err) {
            const errorMessage = err instanceof Error ? err.message : (isEditing ? '修改失败，请重试' : '添加失败，请重试');
            alert(errorMessage);
        }
    };

    const handleEdit = (box: BoxData) => {
        setIsEditing(true);
        setFormData({
            id: box.id,
            boxName: box.boxName,
            long: String(box.long),
            wide: String(box.wide),
            high: String(box.high),
            remark: box.remark || "",
            state: box.state
        });
        setShowModal(true);
    };

    const handleDelete = async (id: number) => {
        // 显示删除确认对话框
        if (window.confirm('您确定要删除这个箱子型号吗？')) {
            try {
                const response = await fetch('http://localhost:5233/api/BoxManage/DeleteBox', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ id }),
                });

                const data = await response.json();

                if (data.code === 200) {
                    // 删除成功
                    await fetchBoxList(); // 先刷新列表
                    setTimeout(() => {
                        alert('删除成功');
                    }, 100);
                } else {
                    // 删除失败
                    throw new Error(data.message || '删除失败');
                }
            } catch (err) {
                const errorMessage = err instanceof Error ? err.message : '删除失败，请重试';
                alert(errorMessage);
            }
        }
        // 如果用户点击取消，对话框会自动关闭，不需要额外处理
    };

    const handleAdd = () => {
        setIsEditing(false);
        setFormData({
            boxName: "",
            long: "",
            wide: "",
            high: "",
            remark: "",
            state: 1
        });
        setShowModal(true);
    };

    const handleCloseModal = () => {
        setShowModal(false);
        setIsEditing(false);
        setFormData({
            boxName: "",
            long: "",
            wide: "",
            high: "",
            remark: "",
            state: 1
        });
        setFormErrors({});
    };

    const getStatusDisplay = (state: number) => {
        return state === 1 ? "启用" : "禁用";
    };

    const handleRefresh = () => {
        if (!refreshing) {
            fetchBoxList();
        }
    };

    const formatNumber = (value: any): string => {
        const num = Number(value);
        return isNaN(num) ? '0.00' : num.toFixed(2);
    };

    return (
        <div className={styles.container}>
            <div className={styles.pageCard}>
                <div className={styles.header}>
                    <h1 className={styles.title}>箱子型号管理</h1>
                    <div className={styles.buttonGroup}>
                        <button 
                            className={styles.addButton} 
                            onClick={handleAdd}
                        >
                            ➕ 箱子型号添加
                        </button>
                        <button 
                            className={styles.refreshButton} 
                            onClick={handleRefresh}
                            disabled={loading || refreshing}
                        >
                            {refreshing ? '刷新中...' : '🔄 刷新'}
                        </button>
                    </div>
                </div>

                {loading && !refreshing && (
                    <div className={styles.loadingContainer}>
                        <p>加载中...</p>
                    </div>
                )}

                {error && (
                    <div className={styles.errorContainer}>
                        <p>错误: {error}</p>
                        <button onClick={handleRefresh} className={styles.retryButton}>
                            重试
                        </button>
                    </div>
                )}

                {!loading && !error && (
                    <table className={styles.table}>
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>名称</th>
                                <th>长（CM）</th>
                                <th>宽（CM）</th>
                                <th>高（CM）</th>
                                <th>备注</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {!Array.isArray(boxList) || boxList.length === 0 ? (
                                <tr>
                                    <td colSpan={8} className={styles.emptyData}>
                                        {!Array.isArray(boxList) ? '数据格式错误' : '暂无数据'}
                                    </td>
                                </tr>
                            ) : (
                                boxList.map((box, index) => (
                                    <tr key={box.id || index}>
                                        <td>{box.id || index + 1}</td>
                                        <td>{box.boxName || '-'}</td>
                                        <td>{formatNumber(box.long)}</td>
                                        <td>{formatNumber(box.wide)}</td>
                                        <td>{formatNumber(box.high)}</td>
                                        <td>{box.remark || '-'}</td>
                                        <td>
                                            <span className={styles.statusBadge}>
                                                {getStatusDisplay(box.state || 0)}
                                            </span>
                                        </td>
                                        <td className={styles.operation}>
                                            <button 
                                                className={styles.edit}
                                                onClick={() => handleEdit(box)}
                                            >
                                                修改
                                            </button>
                                            <button 
                                                className={styles.delete}
                                                onClick={() => handleDelete(box.id)}
                                            >
                                                删除
                                            </button>
                                        </td>
                                    </tr>
                                ))
                            )}
                        </tbody>
                    </table>
                )}

                {/* 添加/修改箱子弹窗 */}
                {showModal && (
                    <div className={styles.modal}>
                        <div className={styles.modalContent}>
                            <div className={styles.modalHeader}>
                                <h2 className={styles.modalTitle}>
                                    {isEditing ? '箱子型号修改' : '箱子型号添加'}
                                </h2>
                                <button className={styles.closeButton} onClick={handleCloseModal}>×</button>
                            </div>
                            <div className={styles.modalBody}>
                                <div className={styles.formGroup}>
                                    <label className={styles.formLabel}>
                                        名称<span className={styles.required}>*</span>
                                    </label>
                                    <div className={styles.formInputWrapper}>
                                        <input
                                            type="text"
                                            className={styles.formInput}
                                            placeholder="请输入"
                                            value={formData.boxName}
                                            onChange={(e) => setFormData({...formData, boxName: e.target.value})}
                                        />
                                        {formErrors.boxName && <div className={styles.error}>{formErrors.boxName}</div>}
                                    </div>
                                </div>
                                <div className={styles.formGroup}>
                                    <label className={styles.formLabel}>
                                        长(CM)<span className={styles.required}>*</span>
                                    </label>
                                    <div className={styles.formInputWrapper}>
                                        <input
                                            type="number"
                                            className={styles.formInput}
                                            placeholder="请输入"
                                            value={formData.long}
                                            onChange={(e) => setFormData({...formData, long: e.target.value})}
                                        />
                                        {formErrors.long && <div className={styles.error}>{formErrors.long}</div>}
                                    </div>
                                </div>
                                <div className={styles.formGroup}>
                                    <label className={styles.formLabel}>
                                        宽(CM)<span className={styles.required}>*</span>
                                    </label>
                                    <div className={styles.formInputWrapper}>
                                        <input
                                            type="number"
                                            className={styles.formInput}
                                            placeholder="请输入"
                                            value={formData.wide}
                                            onChange={(e) => setFormData({...formData, wide: e.target.value})}
                                        />
                                        {formErrors.wide && <div className={styles.error}>{formErrors.wide}</div>}
                                    </div>
                                </div>
                                <div className={styles.formGroup}>
                                    <label className={styles.formLabel}>
                                        高(CM)<span className={styles.required}>*</span>
                                    </label>
                                    <div className={styles.formInputWrapper}>
                                        <input
                                            type="number"
                                            className={styles.formInput}
                                            placeholder="请输入"
                                            value={formData.high}
                                            onChange={(e) => setFormData({...formData, high: e.target.value})}
                                        />
                                        {formErrors.high && <div className={styles.error}>{formErrors.high}</div>}
                                    </div>
                                </div>
                                <div className={styles.formGroup}>
                                    <label className={styles.formLabel}>备注</label>
                                    <div className={styles.formInputWrapper}>
                                        <input
                                            type="text"
                                            className={styles.formInput}
                                            placeholder="请输入"
                                            value={formData.remark}
                                            onChange={(e) => setFormData({...formData, remark: e.target.value})}
                                        />
                                    </div>
                                </div>
                                <div className={styles.formGroup}>
                                    <label className={styles.formLabel}>状态</label>
                                    <div className={styles.formInputWrapper}>
                                        <select
                                            className={styles.formSelect}
                                            value={formData.state}
                                            onChange={(e) => setFormData({...formData, state: Number(e.target.value)})}
                                        >
                                            <option value={1}>启用</option>
                                            <option value={0}>禁用</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div className={styles.modalFooter}>
                                <button className={styles.cancelButton} onClick={handleCloseModal}>
                                    取消
                                </button>
                                <button className={styles.confirmButton} onClick={handleSubmit}>
                                    确认
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default BoxManageQuery;